package com.wbp.cms.web.controller.admin;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.google.gson.Gson;
import com.wbp.cms.client.common.domain.DictionaryDO;
import com.wbp.cms.client.common.query.DictionaryQuery;
import com.wbp.cms.client.common.service.DictionaryService;
import com.wbp.cms.client.constant.CommonConstant;
import com.wbp.cms.client.result.BaseResultCode;
import com.wbp.cms.client.result.Result;
import com.wbp.cms.client.util.JsonUtils;
import com.wbp.cms.web.controller.BaseController;


/**
 * @Description: 
 * @Department:
 * @author andy.lhc
 * @date 2016年3月16日 下午9:06:30 
 */
@Controller("dictionaryMgrController")
@RequestMapping("/dictionarymgr")
public class DictionaryMgrController extends BaseController {

  private static final Logger  logger = Logger.getLogger(ProductMgrController.class) ;
  
  @Resource
  private  DictionaryService  dictionaryService ;
  
  private static final String  dictioanryName ="Dictionary" ;
  
  private static final String  tableName ="tableName" ;
  
  private static final String  attributeName ="attributeName" ;
  /**
   * 进入页面时的方法
   * @return
   */
  @RequestMapping("/tolist")
  public ModelAndView  toList(){
    ModelAndView mv = new ModelAndView();
    mv.setViewName("admin/dictionary/dictionaryList"); 
    
    List<DictionaryDO>  tableList = dictionaryService.queryMetaDictionary(dictioanryName, tableName,0L) ;
    if(tableList !=null)
       mv.addObject("tableList", tableList) ;
    
    return mv ;
  }
  
  /**
   * 通过tableName查找attributeName元数据字典值
   * @param request
   * @param did
   * @return
   */
  @RequestMapping(value="/getattrname", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
  @ResponseBody
  public  String   dogetDictionaryAttribteName(HttpServletRequest request /*,@PathVariable("did") Long did*/
                              , @RequestParam(value = "code", required = true, defaultValue = "") String code ){
    
    if(code.equals(""))
      return JsonUtils.toJson(Result.buildError("code:"+code+",不能为空")) ;
    
    List<DictionaryDO> parentDic = dictionaryService.queryMetaDictionary(dictioanryName,tableName,code) ;
    if(parentDic== null || parentDic.isEmpty())
      return JsonUtils.toJson(Result.buildError("code:"+code+",tableName:"+dictioanryName+",attributeName:"+tableName+",没有查到字典值")) ;
    
    List<DictionaryDO>  attributeList = dictionaryService.queryMetaDictionary(dictioanryName, attributeName,parentDic.get(0).getId()) ;
    
    return  JsonUtils.toJson(Result.buildSuccess(attributeList)) ;
  }
  
  /**
   * to 新增页面
   * @return
   */
  @RequestMapping("/toadd")
  public ModelAndView  toAddDictionary(){
     ModelAndView mv = new ModelAndView();
     mv.setViewName("admin/dictionary/dictionaryAdd"); 
     
     List<DictionaryDO>  tableList = dictionaryService.queryMetaDictionary(dictioanryName, tableName,0L) ;
     if(tableList !=null)
        mv.addObject("tableList", tableList) ;
     
     return  mv ;
  }
  
  /**
   * 保存一条字典类型
   * @param request
   * @return
   */
  @RequestMapping(value="/doadd", method =RequestMethod.POST , produces = "application/json;charset=UTF-8")
  @ResponseBody
  public  String   doAddDictionary(HttpServletRequest request ){
    
    String params = this.getParameters(request).get("params") ; //   request.getParameter("params") ;
    if(params == null  || params.equals(""))
        return JsonUtils.toJson(Result.buildError("参数不合法")) ;
    DictionaryDO dictioanryDO = JsonUtils.toObject(params, DictionaryDO.class) ;
    
    try{
      if(dictioanryDO == null )
        return JsonUtils.toJson(Result.buildError("参数不合法")) ;
      if(StringUtils.isEmpty(dictioanryDO.getTableName()))
        return JsonUtils.toJson(Result.buildError("字典表名称不能为空")) ;
      if(StringUtils.isEmpty(dictioanryDO.getAttributeName()))
        return JsonUtils.toJson(Result.buildError("字典表属性名称不能为空")) ;
      
      dictioanryDO.setDefaultValue(1);
      dictioanryDO.setOrderValue(dictioanryDO.getValue());
      
      List<DictionaryDO> list = this.dictionaryService.queryMetaDictionary(dictioanryName,attributeName,dictioanryDO.getAttributeName()) ; // 数据库只配一个字段描述和表描述
      if(list == null || list.isEmpty() )
        dictioanryDO.setParentId(CommonConstant.DICTIONARY_PARENT_ID_DEFAULT_VALUE);  //default value 
      else
        dictioanryDO.setParentId(list.get(0).getId() ) ;
      
      Long  result = this.dictionaryService.addDictionary(dictioanryDO) ;
      
      return  JsonUtils.toJson(Result.buildSuccess(result)) ;
      
    }catch(Throwable  t){
      logger.error(BaseResultCode.DICTIONARY_ADD_DICTIONARY_ERROR.getErrMsg(), t);
      return JsonUtils.toJson(Result.buildError(BaseResultCode.DICTIONARY_ADD_DICTIONARY_ERROR));
    }
    
   
  }
  
  /**
   * to 编辑页面
   * @param did
   * @return
   */
  @RequestMapping("/toedit")
  public ModelAndView  toEditDictionary(@RequestParam(value="did",required=true,defaultValue="0") Long dictionaryId){
     ModelAndView mv = new ModelAndView();
     mv.setViewName("admin/dictionary/dictionaryEdit"); 
     
     if(dictionaryId >0 )
         mv.addObject("dictioanry",  this.dictionaryService.loadDictionary(dictionaryId)) ;
      
     return  mv ;
  }
  
  /**
   * 编辑保存
   * @param request
   * @return
   */
  @RequestMapping(value="/doedit", method =RequestMethod.POST , produces = "application/json;charset=UTF-8")
  @ResponseBody
  public String  doEditDictionary(HttpServletRequest request  ){
    try{
      
        String params = this.getParameters(request).get("params") ;  
        if(params == null  || params.equals(""))
            return JsonUtils.toJson(Result.buildError("参数不合法")) ;
        DictionaryDO dictioanryDO = JsonUtils.toObject(params, DictionaryDO.class) ;
        if(dictioanryDO == null )
            return JsonUtils.toJson(Result.buildError("参数不合法")) ;
       if(dictioanryDO.getId() == null || dictioanryDO.getId() <=0)
            return JsonUtils.toJson(Result.buildError("id不存在,请重新刷新页面再修改字典类型信息")) ;
        
        boolean  result = this.dictionaryService.modifyDictionary(dictioanryDO) ;
        
        return  JsonUtils.toJson(Result.buildSuccess(result),true) ;
    }catch(Throwable e){
      logger.error(BaseResultCode.DICTIONARY_MODIFY_DICTIONARY_ERROR.getErrMsg(), e);
      return JsonUtils.toJson(Result.buildError(BaseResultCode.DICTIONARY_MODIFY_DICTIONARY_ERROR));
    }
  }
  
  
  /**
   * 删除
   * @return
   */
  @RequestMapping(value="/todelete", produces = "application/json;charset=UTF-8")
  @ResponseBody
  public String  toDelete(@RequestParam(value = "id", required = true, defaultValue = "0") Long id ){
     if(id <=0){
       return JsonUtils.toJson(Result.buildError("id:"+id+",应>0")) ;
     }
     
     boolean b = this.dictionaryService.deleteDictionary(id) ;
     if(!b)
       return JsonUtils.toJson(Result.buildError("id:"+id+"删除字典值出错,请联系管理员")) ;
     
     return JsonUtils.toJson(Result.buildSuccess(b));
  }
  
  
  
  /**
   * 查询
   * @param request
   * @param tableName
   * @param attributeName
   * @param description
   * @param status
   * @param start
   * @param pageSize
   * @return
   */
  @RequestMapping(value="/query", produces = "application/json;charset=UTF-8")
  @ResponseBody
  public String doQuery(HttpServletRequest request,@RequestParam(value = "tableName",
      required = false, defaultValue = "") String tableName, @RequestParam(value = "attributeName",
      required = false, defaultValue = "") String attributeName,@RequestParam(value = "status",
      required = false, defaultValue = "-1") int status , @RequestParam(value = "start",
      required = false, defaultValue = "1") int start,@RequestParam(value = "length",
      required = false, defaultValue = "50") int pageSize) {

    Map<String,String> maps = this.getParameters(request) ;
    
    DictionaryQuery  query =new DictionaryQuery();
    // productQuery.setPageNo(pageNo);
    query.setStart(start);
    query.setPageSize(pageSize);
    if(StringUtils.isNotEmpty(tableName))
      query.setTableName(tableName);
    if(StringUtils.isNotEmpty(attributeName))
      query.setAttributeName(attributeName);
   /* if(StringUtils.isNotEmpty(description))
      query.setDescription(description);*/
    if(status > 0 )
      query.setStatus(status); 
    
    query.setParentId(0L); // ==0 时 查 >0 的字典值
    
    Result<List<DictionaryDO>> result = this.dictionaryService.queryDictionary(query) ;
   
    return new Gson().toJson(getDataTableMapData(result,maps.get(DT_KEY_DRAW) )) ;
     
  } 
  
  
  
}
